<template>
  <view class="container">
    <view class="main">
      <view class="card">
        <view class="input-container">
          <text class="section-title">智能乳制品餐饮推荐</text>
          <!-- 用餐时间 -->
          <view class="form-group">
            <label class="block text-sm font-medium mb-1">用餐时间</label>
            <picker mode="selector" :range="timeOptions" :value="timeIndex" @change="onTimeChange">
              <input type="text" :value="timeOptions[timeIndex]" class="form-control" placeholder="请选择" />
            </picker>
          </view>
          <!-- 体质类型 -->
          <view class="form-group">
            <label class="block text-sm font-medium mb-1">体质类型</label>
            <picker mode="selector" :range="bodyOptions" :value="bodyIndex" @change="onBodyChange">
              <input type="text" :value="bodyOptions[bodyIndex]" class="form-control" placeholder="请选择" />
            </picker>
          </view>
          <!-- 所在城市 -->
          <view class="form-group">
            <label class="block text-sm font-medium mb-1">所在城市</label>
            <input type="text" v-model="cityCondition" class="form-control" placeholder="请输入您所在的城市" />
          </view>
          <!-- 用餐日期 -->
          <view class="form-group">
            <label class="block text-sm font-medium mb-1">用餐日期</label>
            <picker mode="date" :value="dateCondition" @change="onDateChange">
              <input type="text" :value="dateCondition" class="form-control" />
            </picker>
          </view>
          <!-- 获取推荐按钮 -->
          <button class="btn btn-primary" @click="getRecommendations">
            <i class="fa fa-magic"></i> 立即获取推荐
          </button>
        </view>
        <!-- 推荐结果 -->
        <view class="media-previews" v-if="recommendations.length > 0">
          <text class="font-semibold text-lg mb-2">为您推荐的乳制品搭配</text>
          <!-- 修改这里：直接显示整个推荐内容，而不是循环 -->
          <view class="recommend-container">
            {{ recommendations.join('\n\n') }}
          </view>
        </view>
        <view v-else class="empty-tip">暂无符合条件的推荐。</view>
      </view>
      <!-- 食谱智能改良卡片 -->
      <view class="card">
        <view class="input-container">
          <text class="section-title">食谱智能改良</text>
          <view class="form-group">
            <text class="mb-4">您可以对推荐的食谱提出口味反馈，我们的AI系统将为您智能优化</text>
            <br /><br />
            <label class="block text-sm font-medium mb-1">口味反馈</label>
            <textarea v-model="tasteFeedback" rows="4" class="form-control" placeholder="请输入您的口味反馈（比如太甜、太腻、希望更清淡等）"></textarea>
          </view>
          <view class="flex flex-col sm:flex-row justify-between items-center gap-4">
            <button class="btn btn-success" @click="submitFeedback">
              <i class="fa fa-paper-plane"></i> 提交反馈
            </button>
            <view v-if="improvedRecipe" class="w-full sm:w-auto">
              <text class="font-semibold text-lg mb-1 block">改良后食谱</text>
              <!-- 修改这里：使用white-space保留换行符 -->
              <view class="form-control bg-gray-50 min-h-[64rpx] py-2 px-4 rounded border-none recipe-text">
                {{ improvedRecipe || '等待反馈...' }}
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import getHeader from '@/api/api.js'
export default {
  data() {
    return {
      timeOptions: ['请选择', '早餐', '午餐', '晚餐', '加餐'],
      timeIndex: 0,
      bodyOptions: ['请选择', '平和质', '阳虚质', '阴虚质', '湿热质'],
      bodyIndex: 0,
      cityCondition: '',
      dateCondition: new Date().toISOString().split('T')[0],
      recommendations: [],
      tasteFeedback: '',
      improvedRecipe: ''
    };
  },
  methods: {
    goToCustomDish() {
      uni.navigateTo({
        url: '/pages/customDish/customDish'
      });
    },
    onTimeChange(e) {
      this.timeIndex = e.detail.value;
    },
    onBodyChange(e) {
      this.bodyIndex = e.detail.value;
    },
    onDateChange(e) {
      this.dateCondition = e.detail.value;
    },
    async getRecommendations() {
      const mealTime = this.timeOptions[this.timeIndex];
      const constitution = this.bodyOptions[this.bodyIndex];
      const mealDate = this.dateCondition;
      const city = this.cityCondition.trim() || '未知城市';

      if (!mealTime || mealTime === '请选择' || !constitution || constitution === '请选择' || !mealDate) {
        uni.showToast({
          title: '请至少选择用餐时间、体质类型和日期',
          icon: 'none'
        });
        return;
      }

      try {
        uni.showLoading({
          title: '获取中...'
        });
        this.recommendations = [];

        const queryParams = new URLSearchParams({
          mealTime,
          constitution,
          mealDate,
          city,
          requestType: 'recommendation'
        });

        const headers = getHeader();
        console.log('[请求头信息]', headers);
        console.log('[请求URL]', `/api/cuisine?${queryParams}`);

        const res = await uni.request({
          url: `/api/cuisine?${queryParams}`,
          method: 'GET',
          header: headers
        });

        console.log('[接口响应]', res);

        if (res.statusCode < 200 || res.statusCode >= 300) {
          throw new Error(`接口请求失败，状态码: ${res.statusCode}，详情: ${res.errMsg || '无明确错误信息'}`);
        }

        const responseData = res[1];
        
        if (!responseData || responseData.errMsg !== 'request:ok') {
          throw new Error(`业务错误: ${responseData?.errMsg || '未知错误'}`);
        }

        // 处理推荐结果 - 修改这里：直接将返回的数据作为单个推荐内容
        if (responseData.data) {
          // 如果后端返回的是数组，合并为一个字符串
          if (Array.isArray(responseData.data)) {
            this.recommendations = [responseData.data.join('\n\n')];
          } else {
            // 如果返回的是字符串，直接作为单个推荐
            this.recommendations = [responseData.data];
          }
        } else {
          this.recommendations = [];
          uni.showToast({
            title: '未找到符合条件的推荐',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('[获取乳制品推荐失败]', error);
        uni.showToast({
          title: `推荐请求失败: ${error.message || '未知错误'}`,
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    async submitFeedback() {
      const feedback = this.tasteFeedback.trim();

      if (!feedback) {
        uni.showToast({
          title: '请填写口味反馈',
          icon: 'none'
        });
        return;
      }

      try {
        uni.showLoading({
          title: '处理中...'
        });
        this.improvedRecipe = '正在生成改良建议...';

        const headers = getHeader();
        console.log('[请求头信息]', headers);
        console.log('[请求URL]', '/api/cuisine');
        console.log('[请求体]', { feedback, requestType: 'improvement' });

        const res = await uni.request({
          url: '/api/cuisine',
          method: 'PUT',
          header: headers,
          data: {
            feedback: feedback,
            requestType: 'improvement'
          }
        });

        console.log('[接口响应]', res);

        if (res.statusCode < 200 || res.statusCode >= 300) {
          throw new Error(`接口请求失败，状态码: ${res.statusCode}，详情: ${res.errMsg || '无明确错误信息'}`);
        }

        const responseData = res[1];
        
        if (!responseData || responseData.errMsg !== 'request:ok') {
          throw new Error(`业务错误: ${responseData?.errMsg || '未知错误'}`);
        }

        // 处理改良结果 - 修改这里：直接获取data中的improvement字段
        if (responseData.data && responseData.data.improvement) {
          this.improvedRecipe = responseData.data.improvement;
        } else if (responseData.data) {
          // 如果没有improvement字段，尝试直接使用data
          this.improvedRecipe = responseData.data.toString();
        } else {
          this.improvedRecipe = '暂无改良建议';
        }
      } catch (error) {
        console.error('[获取改良后食谱失败]', error);
        this.improvedRecipe = `获取失败: ${error.message || '未知错误'}`;
        uni.showToast({
          title: `改良请求失败: ${error.message || '未知错误'}`,
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    }
  }
};
</script>

<style scoped>
:root {
  --base-font-size: 24rpx;
  --base-padding: 12rpx;
  --base-border-radius: 6rpx;
}

.container {
  max-width: 750rpx;
  margin: 0 auto;
  padding: 0 30rpx;
}

.card {
  background-color: white;
  border-radius: 8rpx;
  box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.1);
  padding: 40rpx;
  margin-bottom: 40rpx;
}

.btn {
  padding: var(--base-padding) 24rpx;
  border-radius: var(--base-border-radius);
  font-size: var(--base-font-size);
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
  outline: none;
  width: 100%;
}

.btn-primary {
  background-color: #409EFF;
  color: white;
}

.btn-success {
  background-color: #67C23A;
  color: white;
}

.form-control {
  display: block;
  width: 100%;
  min-height: 64rpx;
  padding: var(--base-padding) 20rpx;
  font-size: var(--base-font-size);
  line-height: 1.4;
  color: #606266;
  background-color: white;
  border: 2rpx solid #dcdfe6;
  border-radius: var(--base-border-radius);
  box-sizing: border-box;
  vertical-align: middle;
}

.input-container {
  max-width: 90%;
  margin: 0 auto;
}

.form-group {
  margin-bottom: 30rpx;
}

.main {
  padding: 60rpx 0;
}

.section-title {
  font-size: 20rpx;
  font-weight: 750;
  margin: 0 0 30rpx 0;
}

.media-previews {
  margin-top: 40rpx;
}

.font-semibold {
  font-weight: 600;
}

.text-lg {
  font-size: 32rpx;
}

.mb-1 {
  margin-bottom: 8rpx;
}

.mb-2 {
  margin-bottom: 10rpx;
}

.mb-4 {
  margin-bottom: 20rpx;
}

.max-w-full {
  max-width: 100%;
}

.h-auto {
  height: auto;
}

.rounded {
  border-radius: 8rpx;
}

.shadow {
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.empty-tip {
  color: #909399;
  text-align: center;
  padding: 40rpx 0;
  font-size: var(--base-font-size);
}

.recommend-item {
  border: 2rpx solid #ebeef5;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: var(--base-font-size);
}

.grid {
  display: grid;
  gap: 20rpx;
}

.grid-cols-1 {
  grid-template-columns: repeat(1, minmax(0, 1fr));
}

/* 新增样式：保留换行符 */
.recipe-text {
  white-space: pre-wrap;
}

.recommend-container {
  border: 2rpx solid #ebeef5;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: var(--base-font-size);
  white-space: pre-wrap;
}
</style>